package com.linln.admin.pcs.api;

import com.linln.admin.config.IDCardEncryptor;
import com.linln.admin.config.JwtTokenUtil;
import com.linln.admin.config.SmsUtils;
import com.linln.admin.pcs.service.OrderTempService;
import com.linln.common.data.PageSort;
import com.linln.common.data.QuerySpec;
import com.linln.common.exception.ResultException;
import com.linln.common.utils.DateUtils;
import com.linln.common.utils.EncryptUtil;
import com.linln.common.utils.HttpServletUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.fileUpload.FileUpload;
import com.linln.component.fileUpload.enums.UploadResultEnum;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import com.linln.modules.system.service.OrderAmountsService;
import com.linln.modules.system.service.OrderPortersService;
import com.linln.modules.system.service.SmsLogService;
import com.linln.modules.system.service.UploadService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 平板端
 */
@RestController
@RequestMapping("/api/slab/")
public class SlabApiController {

    private final static Logger logger = LoggerFactory.getLogger(SlabApiController.class);

    @Value("${securitys.slabKey}")
    private  String SECRET_KEY;

    @Autowired
    private PorterRepository porterRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private PorterPermissionRepository porterPermissionRepository;

    @Autowired
    private OrderPortersRepository orderPortersRepository;

    @Autowired
    private OrderLogsRepository orderLogsRepository;

    @Autowired
    private PatientRepository patientRepository;

    @Autowired
    private CompanyRepository companyRepository;

    @Autowired
    private OrderAmountsRepository orderAmountsRepository;

    @Autowired
    private OrderAmountsService orderAmountsService;

    @Autowired
    private ProjectRepository projectRepository;

    @Autowired
    private ContractTplRepository contractTplRepository;

    @Autowired
    private SmsLogService smsLogService;

    @Autowired
    private OrderPortersService orderPortersService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Autowired
    private ComplainRepository complainRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OrderTempService orderTempService;
    @Autowired
    private MsgRepository msgRepository;
    /**
     * 登录
     */
    @PostMapping("login")
    public ResultVo login(@RequestBody Company companys) {
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("type", QuerySpec.EQUAL,"2")
                .withMatcherValue("username", QuerySpec.EQUAL,companys.getName());
        List<User> userList = userRepository.findAll(QuerySpec.of(querySpec));
        if (userList.size()>0){
            User user = userList.get(0);
            String password = companys.getPassword();
            // 对明文密码加密处理
            String encrypt = EncryptUtil.encrypt(password, user.getSalt());
            if (user.getPassword().equals(encrypt)){
                String token = jwtTokenUtil.generateToken(user.getUsername(),SECRET_KEY);
                Map<String, Object> result = new HashMap<>();
                result.put("token", token);
                Company company = companyRepository.findById(user.getCompanyId()).get();
                company.setLegalPhone(IDCardEncryptor.aesDecrypt(company.getLegalPhone()));
                company.setLegalCardNo(IDCardEncryptor.aesDecrypt(company.getLegalCardNo()));
                result.put("company", company);
                return ResultVoUtil.success("登录成功",result);
            }else {
                return ResultVoUtil.error("密码错误");
            }
        }
        return ResultVoUtil.error("未找到公司");
    }


    /**
     * 服务列表
     */
    @GetMapping("service/list")
    public ResultVo statisticsService(@RequestParam int serviceType,@RequestParam String companyId){
        List<Porter> list = new ArrayList<>();
        Page<Porter> all = null;
        //1、全部 2未服务 3服务中
        if (serviceType==1) {
            QuerySpec querySpec = QuerySpec.matching();
            querySpec.withMatcher("name", QuerySpec.LIKE)
                    .withMatcherValue("companyId", QuerySpec.EQUAL,companyId)
                    .withMatcherValue("status", QuerySpec.EQUAL,"1");
            PageRequest pageRequest = PageSort.pageRequest(1, "id", Sort.Direction.DESC);
            all = porterRepository.findAll(QuerySpec.of(querySpec), pageRequest);
            list = all.getContent();
        }else if (serviceType==2) {
            QuerySpec querySpec1 = QuerySpec.matching();
            List<Object> statusList = new LinkedList<>();
            statusList.add(0);
            statusList.add(1);
            statusList.add(2);
            statusList.add(3);
            statusList.add(4);
            //查询历史订单
            querySpec1.withMatcherValue("status", QuerySpec.EQUAL,"1")
                    .withMatcherIn("orderStatus",statusList);
            List<Order> orderTempList = orderRepository.findAll(QuerySpec.of(querySpec1));

            List<Object> porterIdList = new LinkedList<>();
            for (Order order : orderTempList){
                if (null!=order.getPorterId()){
                    porterIdList.add(order.getPorterId());
                }
            }
            if (porterIdList.size()>0){
                QuerySpec querySpec = QuerySpec.matching();
                querySpec.withMatcher("name", QuerySpec.LIKE)
                        .withMatcherValue("companyId", QuerySpec.EQUAL,companyId)
                        .withMatcherValue("status", QuerySpec.EQUAL,"1")
                        .withMatcherNotIn("id",porterIdList);
                PageRequest pageRequest = PageSort.pageRequest(1, "id", Sort.Direction.DESC);
                all = porterRepository.findAll(QuerySpec.of(querySpec), pageRequest);
                list = all.getContent();
            }else{
                QuerySpec querySpec = QuerySpec.matching();
                querySpec.withMatcher("name", QuerySpec.LIKE)
                        .withMatcherValue("companyId", QuerySpec.EQUAL,companyId)
                        .withMatcherValue("status", QuerySpec.EQUAL,"1");
                PageRequest pageRequest = PageSort.pageRequest(1, "id", Sort.Direction.DESC);
                all = porterRepository.findAll(QuerySpec.of(querySpec), pageRequest);
                list = all.getContent();
            }


        }else if (serviceType==3) {
            QuerySpec querySpec1 = QuerySpec.matching();
            List<Object> statusList = new LinkedList<>();
            statusList.add(0);
            statusList.add(1);
            statusList.add(2);
            statusList.add(3);
            statusList.add(4);
            //查询历史订单
            querySpec1.withMatcherValue("status", QuerySpec.EQUAL,"1")
                    .withMatcherIn("orderStatus",statusList);
            List<Order> orderTempList = orderRepository.findAll(QuerySpec.of(querySpec1));

            List<Object> porterIdList = new LinkedList<>();
            for (Order order : orderTempList){
                if (null!=order.getPorterId()){
                    porterIdList.add(order.getPorterId());
                }
            }
            if (porterIdList.size()>0){
                QuerySpec querySpec = QuerySpec.matching();
                querySpec.withMatcher("name", QuerySpec.LIKE)
                        .withMatcherValue("companyId", QuerySpec.EQUAL,companyId)
                        .withMatcherValue("status", QuerySpec.EQUAL,"1")
                        .withMatcherIn("id",porterIdList);
                PageRequest pageRequest = PageSort.pageRequest(1, "id", Sort.Direction.DESC);
                all = porterRepository.findAll(QuerySpec.of(querySpec), pageRequest);
                list = all.getContent();
            }

        }
        List<Object> porterIds = new LinkedList<>();
        for (Porter porter : list){
            porterIds.add(porter.getId());
        }
        //当前服务次数统计
        QuerySpec querySpec1 = QuerySpec.matching();
        List<Object> statusTpList = new ArrayList<>();
        statusTpList.add(0);
        statusTpList.add(1);
        statusTpList.add(2);
        statusTpList.add(3);
        statusTpList.add(4);
        querySpec1.withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherIn("orderStatus",statusTpList)
                .withMatcherIn("porterId",porterIds);
        List<Order> orderList = orderRepository.findAll(QuerySpec.of(querySpec1));

        //累计服务
        List<Object> statusList = new ArrayList<>();
        statusList.add(2);
        QuerySpec querySpec2 = QuerySpec.matching();
        querySpec2.withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("orderType", QuerySpec.EQUAL,"1")
                .withMatcherIn("serviceStatus",statusList)
                .withMatcherIn("porterId",porterIds);
        List<OrderPorters> orderPortersList = orderPortersRepository.findAll(QuerySpec.of(querySpec2));

        //查询所有护理科室
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("verifyStatus", QuerySpec.EQUAL,"1")
                .withMatcherIn("porterId", porterIds);
        List<PorterPermission> permissionList = porterPermissionRepository.findAll(QuerySpec.of(querySpec));
        for (Porter porter : list){
            Long porterId = porter.getId();
            //查询所有护理科室
            List<PorterPermission> permissions = new LinkedList<>();
            for (PorterPermission porterPermission : permissionList){
                if (porterId.equals(porterPermission.getPorterId())){
                    permissions.add(porterPermission);
                }
            }
            porter.setPorterPermissions(permissions);

            //累计服务次数
            int serviceNum = 0;
            for (OrderPorters orderPorters : orderPortersList){
                if (porterId.equals(orderPorters.getPorterId())){
                    serviceNum++;
                }
            }
            porter.setServiceNum(serviceNum);

            //服务状态  1未服务 2服务中
            int serviceStatus = 1;
            for (Order order : orderList){
                if (porterId.equals(order.getPorterId())){
                    int orderStatus = order.getOrderStatus();
                    serviceStatus = 2;
                    break;
                }
            }
            porter.setServiceStatus(serviceStatus);

            //定义陪护 陪诊 陪检
            int serviceNumber = 0;
            int pzNumber = 0;
            int pjNumber = 0;
            for (Order order : orderList){
                if (porterId.equals(order.getPorterId())){
                    int orderStatus = order.getOrderStatus();
                    int type = order.getType();
                    if (type==1) {
                        serviceNumber++;
                    } else if (type==2) {
                        pzNumber++;
                    } else if (type==3) {
                        pjNumber++;
                    }
                }
            }
            porter.setServiceNumber(serviceNumber);
            porter.setPzNumber(pzNumber);
            porter.setPjNumber(pjNumber);
        }
        Map<String,Object> map = new HashMap<>();
        if (all!=null){
            map.put("totalPages",all.getTotalElements());
            map.put("list",list);
        }else{
            map.put("totalPages",0);
            map.put("list",list);
        }
        return ResultVoUtil.success("服务列表",map);
    }

    /**
     * 陪护陪诊陪检服务详情
     * @param type
     * @param porterId
     * @return
     */
    @RequestMapping("check/service")
    public ResultVo checkService(@RequestParam int type,@RequestParam String porterId) {
        QuerySpec querySpec1 = QuerySpec.matching();
        List<Object> statusList = new LinkedList<>();
        statusList.add(0);
        statusList.add(1);
        statusList.add(2);
        statusList.add(3);
        statusList.add(4);
        querySpec1.withMatcherValue("porterId", QuerySpec.EQUAL,String.valueOf(porterId))
                .withMatcherValue("status", QuerySpec.EQUAL,"1")
                .withMatcherValue("type", QuerySpec.EQUAL, String.valueOf(type))
                .withMatcherIn("orderStatus", statusList);
        List<Order> orderList = orderRepository.findAll(QuerySpec.of(querySpec1));
        return ResultVoUtil.success("服务详情",orderList);
    }

    /**
     * 查看订单
     * @param orderId
     * @return
     */
    @RequestMapping("check/order")
    public ResultVo serviceOrder(@RequestParam String orderId) {
        Order order = orderRepository.findById(Long.valueOf(orderId)).get();
        //患者信息
        Patient patient = patientRepository.findById(order.getPatientId()).get();
        patient.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(patient.getPhone()));
        patient.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo()));
        order.setPatient(patient);

        //查询投诉
        QuerySpec querySpec2 = QuerySpec.matching();
        querySpec2.withMatcherValue("sn", QuerySpec.EQUAL,order.getSn())
                .withMatcherValue("status", QuerySpec.EQUAL,String.valueOf(1));
        List<Complain> complainList = complainRepository.findAll(QuerySpec.of(querySpec2));
        if (complainList.size()>0){
            order.setComplain(complainList.get(0));
        }

        //服务护工
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("orderId", QuerySpec.EQUAL, orderId)
                .withMatcherValue("status", QuerySpec.EQUAL,String.valueOf(1))
                .withMatcherValue("orderType", QuerySpec.EQUAL,String.valueOf(order.getType()))
                .withMatcherValue("serviceStatus", QuerySpec.GT,"-1");
        List<OrderPorters> orderPortersList = orderPortersRepository.findAll(QuerySpec.of(querySpec));
        for (OrderPorters orderPorters : orderPortersList){
            Porter porter = porterRepository.findById(orderPorters.getPorterId()).get();
            //更换方式1默认2患者申请更换3公司更换
            porter.setChangeStatus(orderPorters.getType());
            Date createTime = orderPorters.getUpdateTime();
            porter.setChangeTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM,createTime));
            orderPorters.setPorter(porter);
        }
        order.setAllServiceNumber(order.getNum()+"");
        order.setOrderPortersList(orderPortersList);
        //服务日志
        QuerySpec querySpec1 = QuerySpec.matching();
        querySpec1.withMatcherValue("orderId", QuerySpec.EQUAL, orderId)
                .withMatcherValue("status", QuerySpec.EQUAL,String.valueOf(1));
        List<OrderLogs> orderLogList = orderLogsRepository.findAll(QuerySpec.of(querySpec1),Sort.by(Sort.Direction.ASC,"createDay"));
        List<TempParam> list= new ArrayList<>();
        if (orderLogList.size()>0){
            String createDay1 = orderLogList.get(0).getCreateDay();
            int m = 0;
            for (int i=0;i<orderLogList.size();i++){
                List<OrderLogs> orderLogsList = new ArrayList<>();
                for (;m<orderLogList.size();){
                    OrderLogs orderLogs = orderLogList.get(m);
                    String createDay = orderLogs.getCreateDay();
                    if (StringUtils.isNotEmpty(createDay)&&createDay1.equals(createDay)){
                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, orderLogs.getCreateTime());
                        String[] s1 = s.split(" ");
                        orderLogs.setTimes(s1[1]);
                        orderLogsList.add(orderLogs);
                        m++;
                    }else{
                        TempParam tempParam = new TempParam();
                        tempParam.setDay(createDay1);
                        tempParam.setHeadImg(orderLogs.getPorterImg());
                        tempParam.setName(orderLogs.getPorterName());
                        tempParam.setOrderLogsList(orderLogsList);
                        list.add(tempParam);
                        createDay1 = createDay;
                        break;
                    }
                }
                if (m==orderLogList.size()){
                    //最后一个补充上去
                    OrderLogs orderLogs = orderLogList.get(orderLogList.size() - 1);
                    TempParam tempParam = new TempParam();
                    tempParam.setDay(createDay1);
                    tempParam.setHeadImg(orderLogs.getPorterImg());
                    tempParam.setName(orderLogs.getPorterName());
                    tempParam.setOrderLogsList(orderLogsList);
                    list.add(tempParam);
                    break;
                }
            }
        }
        order.setTempParamList(list);
        return ResultVoUtil.success("查看订单",order);
    }

    /**
     * 合同列表
     * @param type  1、全部 2、待签订 3、已签订
     * @param companyId
     * @return
     */
    @RequestMapping("order/list")
    public ResultVo orderList(@RequestParam int type,@RequestParam String companyId){
        List<Order> orderList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        if (type==1){
            PageRequest pageRequest = PageSort.pageRequest(1, "id", Sort.Direction.DESC);
            Page<Order> all = orderRepository.selectAllCompanyIdAndOrderStatus(Long.parseLong(companyId), pageRequest);
            orderList = all.getContent();
            map.put("totalPages",all.getTotalElements());
            for (Order order : orderList){
                Porter porter = porterRepository.findById(order.getPorterId()).get();
                order.setPorter(porter);
            }
        } else if (type == 2) {
            PageRequest pageRequest = PageSort.pageRequest(1, "id", Sort.Direction.DESC);
            Page<Order> all = orderRepository.selectWaitCompanyIdAndOrderStatus(Long.parseLong(companyId), pageRequest);
            orderList = all.getContent();
            map.put("totalPages",all.getTotalElements());
            for (Order order : orderList){
                Porter porter = porterRepository.findById(order.getPorterId()).get();
                order.setPorter(porter);
            }
        }else{
            PageRequest pageRequest = PageSort.pageRequest(1, "id", Sort.Direction.DESC);
            Page<Order> all = orderRepository.selectAftCompanyIdAndOrderStatus(Long.parseLong(companyId), pageRequest);
            orderList = all.getContent();
            map.put("totalPages",all.getTotalElements());
            for (Order order : orderList){
                Porter porter = porterRepository.findById(order.getPorterId()).get();
                order.setPorter(porter);
            }
        }
        map.put("list",orderList);
        return ResultVoUtil.success("合同列表",map);
    }

    /**
     * 合同内容
     * @param orderId
     * @return
     */
    @RequestMapping("check/contract")
    public ResultVo checkContract(@RequestParam String orderId) throws Exception {
        Order order = orderRepository.findById(Long.valueOf(orderId)).get();
        Long projectId = order.getProjectId();
        Project project = projectRepository.getById(projectId);
        Patient patient = patientRepository.getById(order.getPatientId());
        if (null == project.getContractTplId()){
            return ResultVoUtil.error("请先设置合同模板");
        }
        ContractTpl contractTpl = contractTplRepository.findById(project.getContractTplId()).get();
        String cardNo = IDCardEncryptor.aesDecrypt(patient.getCardNo());
        contractTpl.setCardNo(cardNo);
        contractTpl.setName(patient.getName());
        String phone = IDCardEncryptor.aesDecrypt(patient.getPhone());
        contractTpl.setPhone(phone);
        contractTpl.setOrderId(Long.valueOf(orderId));
        contractTpl.setPic(order.getPic());
        return ResultVoUtil.success("合同内容",contractTpl);
    }

    /**
     * 签订合同
     * @param order
     * @return
     */
    @PostMapping("sign/order")
    @Transactional(rollbackFor = Exception.class)
    public ResultVo signOrder(@RequestBody Order order){
        Order order1 = orderRepository.findById(order.getId()).get();
        int type = order1.getType();
        String dates = DateUtils.getDates();
        order1.setSignCont(order.getSignCont());
        order1.setPic(order.getPic());
        order1.setSignTime(dates);
        order1.setSignStatus((byte) 1);
        order1.setConcludeTime(dates);
        //1 陪护 2 陪诊 3 陪检
        if (type==2||type==3){
            //如果是陪诊陪检  签订完合同直接开始服务
            order1.setOrderStatus(2);
            //扣除费用
            order1.setNum(1);
            order1.setTotal(order1.getPrice());
            //更新记录
            orderPortersService.updatePorterOrder(order1.getId(),order1.getPorterId(),0L,order1.getCompanyId(),1,order1.getStartDay(),"",1,order1.getType());
            //金额变动表
            orderAmountsService.updateOrderAmounts(order1,"患者费用扣除",1);
        }else{
            int settlementType = order1.getSettlementType();
            if(settlementType==1){
                order1.setOrderStatus(3);
            }else{
                order1.setOrderStatus(4);
                //修改预交费状态
                order1.setBeforeStatus((byte) 1);
                order1.setIsSettled(2);
            }
        }
        orderRepository.save(order1);
        return ResultVoUtil.success("签订合同",order1);
    }

    /**
     * 开始计费
     * @param order
     * @return
     */
    @PostMapping("start/order")
    @Transactional(rollbackFor = Exception.class)
    public ResultVo startOrder(@RequestBody Order order){
        Order order1 = orderRepository.findById(order.getId()).get();
        //1 陪护 2 陪诊 3 陪检
        int type = order1.getType();
        if (type==1){
            orderTempService.jifei(order.getId(),order.getStartDay());
            return ResultVoUtil.success("开始计费",order1);
        }else{
            return ResultVoUtil.error("该订单不是陪护订单");
        }
    }

    /**
     * 所有订单列表
     * @param companyId
     */
    @RequestMapping("order/page")
    public ResultVo orderPage(@RequestParam String companyId){
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL, companyId)
                .withMatcher("orderStatus", QuerySpec.EQUAL)
                .withMatcherValue("type",  QuerySpec.EQUAL,"1");
        PageRequest page = PageSort.pageRequest(100, "id", Sort.Direction.DESC);
        Page<Order> orderList = orderRepository.findAll(QuerySpec.of(querySpec),page);
        Map<String,Object> map = new HashMap<>();
        map.put("totalPages",orderList.getTotalElements());
        map.put("list",orderList.getContent());
        return ResultVoUtil.success("所有订单列表",map);
    }

    /**
     * 订单确认
     */
    @PostMapping("order/confirm")
    @Transactional(rollbackFor = Exception.class)
    public ResultVo confirm(@RequestBody Order orderRequest){
        Order order = orderRepository.findById(orderRequest.getId()).get();
        //1 陪护 2 陪诊 3 陪检
        int type = order.getType();
        if(order.getIsWl()==1){
            return ResultVoUtil.error("该订单为五类人员订单");
        }
        if (type==1){
            Integer settlementType = orderRequest.getSettlementType();
            order.setSettlementType(settlementType);
            if(order.getIsNeedSignContract()==1){
                order.setOrderStatus(1);
            }else{
                if(settlementType==1){
                    order.setOrderStatus(3);
                    order.setConcludeTime(DateUtils.getDates());
                }else{
                    order.setOrderStatus(4);
                    //修改预交费状态
                    order.setBeforeStatus((byte) 1);
                    order.setIsSettled(2);
                }
            }
            orderRepository.save(order);
            //发送消息
            Msg msg = new Msg();
            msg.setType((byte) 2);
            msg.setPatientId(order.getPatientId());
            msg.setSn(order.getSn());
            msg.setContent("您好!您的订单["+order.getProjectTitle()+"]已确认,我们已通知陪护员赶往您所在的病区,请耐心等待!");
            msg.setStatus((byte) 1);
            msgRepository.save(msg);
            Patient patient = patientRepository.findById(order.getPatientId()).orElse(null);
            if(patient!=null){
                String openId = patient.getOpenid();
                if(openId!=null&& !openId.equals("")){
                    //发送模板消息
                    try {
                        String content = "您的订单("+order.getProjectTitle()+")已确认,请及时进入系统查看!";
                        String ss = IDCardEncryptor.aesDecrypt(patient.getPhone());
                        String r = SmsUtils.sendSms(ss,content);
                        smsLogService .insert(order.getSn(),patient.getPhone(),4,3,patient.getId(),r,r);
                    } catch (Exception e) {
                        // 空catch块直接忽略异常，或添加日志记录
                        // log.error("模板消息发送失败", e);
                    }
                }
            }
            return ResultVoUtil.success("订单确认",order);
        }else{
            return ResultVoUtil.error("该订单不是陪护订单");
        }
    }

    /**
     * 五类人员订单确认
     */
    @PostMapping("order/confirm_wl")
    @Transactional(rollbackFor = Exception.class)
    public ResultVo confirmWl(@RequestBody Order orderRequest){
        Order order = orderRepository.findById(orderRequest.getId()).get();
        //1 陪护 2 陪诊 3 陪检
        int type = order.getType();
        if(order.getIsWl()==0){
            return ResultVoUtil.error("该订单为非五类人员订单");
        }
        if (type==1){
            Integer settlementType = 2;
            order.setSettlementType(settlementType);
            order.setOrderStatus(4);
            //修改预交费状态
            order.setBeforeStatus((byte) 1);
            order.setIsSettled(2);
            Long porterId = orderRequest.getPorterId();
            if(porterId==null || porterId==0){
                return ResultVoUtil.error("请选择护工");
            }
            Porter porter = porterRepository.getById(porterId);
            if(porter==null){
                return ResultVoUtil.error("请选择正确的护工");
            }
            order.setPorterId(porterId);
            order.setPorterName(porter.getName());
            order.setPorterPhone(porter.getPhone());
            orderRepository.save(order);
            String startDay = DateUtils.getDate();
            orderTempService.jifei(order.getId(),startDay);
            //发送消息
            Msg msg = new Msg();
            msg.setType((byte) 2);
            msg.setPatientId(order.getPatientId());
            msg.setSn(order.getSn());
            msg.setContent("您好!您的订单["+order.getProjectTitle()+"]已确认,我们已通知陪护员赶往您所在的病区,请耐心等待!");
            msg.setStatus((byte) 1);
            msgRepository.save(msg);
            Patient patient = patientRepository.findById(order.getPatientId()).orElse(null);
            if(patient!=null){
                String openId = patient.getOpenid();
                if(openId!=null&& !openId.equals("")){
                    //发送模板消息
                    try {
                        String content = "您的订单("+order.getProjectTitle()+")已确认,请及时进入系统查看!";
                        String ss = IDCardEncryptor.aesDecrypt(patient.getPhone());
                        String r = SmsUtils.sendSms(ss,content);
                        smsLogService .insert(order.getSn(),patient.getPhone(),4,3,patient.getId(),r,r);
                    } catch (Exception e) {
                        // 空catch块直接忽略异常，或添加日志记录
                        // log.error("模板消息发送失败", e);
                    }
                }
            }
            return ResultVoUtil.success("订单确认",order);
        }else{
            return ResultVoUtil.error("该订单不是陪护订单");
        }
    }

    /**
     * 五类人员订单确认选择的护工列表
     */
    @RequestMapping("/confirm_wl/porterList")
    public ResultVo porterList(@RequestParam Long companyId){
        List<Porter> porterList = porterRepository.findAll(QuerySpec.of(QuerySpec.matching().withMatcherValue("companyId", QuerySpec.EQUAL, String.valueOf(companyId))));
        return ResultVoUtil.success("获取成功",porterList);
    }

}
